;$(function() {
	var serverIdArr='';
	var id = $("#id").val();
	getDeptList();//获取部门
	if(id==null||id==''){
		upload(serverIdArr)
    }else{
    	$("#password").hide();
    	$("#username").attr("disabled",true);;
    	getInfo(id,serverIdArr);	
    }
	submitForm();
})
 var tale = new $.tale();//弹框
function upload(serverIdArr){
    $("#dropzone").dropzone({
        paramName: "file",
        url: ctxPath+"/file/upload",
        addRemoveLinks: true,
        dictRemoveLinks: "x",
//        uploadMultiple: true,
        maxFilesize: 10,
        init: function () {
            this.on("success", function (file, msg) {
               	file.serverId=msg.message;
               	serverIdArr=msg.message;
            	$("#image_files").val(serverIdArr);
            });
            this.on('error', function (files, response) {
                //文件上传失败后的操作
            	console.log(files, response);
            });
            //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
            this.on("removedfile", function (file) {
            	$("#image_files").val("");
            });
        }
    });
}
/**
 * 获取组织机构
 * @returns
 */
function getDeptList(){
	$.ajax({
        url: ctxPath+"/agency/dept/getAllList",
        type: 'GET',
        success: function(d){
        	var success = d.success;
        	 if(success==true){
        	if(d.data!=null){
        		var result ='<option value="">请选择</option>';
        		
        	$.each(d.data,function(i,item){
        		result+='<option value="'+item.id+'">'+item.name+'</option>';	
        	})
        	$("#dept_select").html(result);
        	}	 
        	}
        	 
	}
        })
}

function getInfo(id,serverIdArr){
	    if(id==null||id==''){
	    	return;
	    }
	   $.ajax({
        url: ctxPath+"/agency/user/findById/"+id,
        type: 'GET',
        success: function(d){
        	var success = d.success;
        	 if(success==true){
        	 var data=  d.data;
        	 umbinding.bind(data);
        	 toHtml(data);
        	 serverIdArr=data.fileId;
        	 $("#image_files").val(serverIdArr);
        	 var myDropzone = new Dropzone("#dropzone", {
        	        paramName: "file",
        	        url: ctxPath+"/file/upload",
        	        addRemoveLinks: true,
        	        dictRemoveLinks: "x",
//        	        uploadMultiple: true,
        	        maxFiles: 3,
        	        maxFilesize: 10,
        	        init: function () {
        	            this.on("success", function (file, msg) {
        	               	file.serverId=msg.message;
        	               	serverIdArr=msg.message;
        	            	$("#image_files").val(serverIdArr);
        	            });
        	            this.on('error', function (files, response) {
        	            });
        	            //删除图片的事件，当上传的图片为空时，使上传按钮不可用状态
        	            this.on("removedfile", function (file) {
        	            	$("#image_files").val("");
        	            });
        	        }
        	    });
        	 if(data.files!=null){
        	  for (var i = 0; i < data.files.length; i++) {
        		   var size = data.files[i].size*1024;
        			 var mockFile = { 
        					 name: data.files[i].srcname,
        					 accepted:true,
        					 size: size, //图片尺寸
    					     height:"70%",
    					     width:"70%",
    					     type:'.jpg,.png,.gif'//图片文件类型
        					    };
                	 myDropzone.emit("addedfile", mockFile);
                	 myDropzone.emit("thumbnail", mockFile, ctxPath+"/file/showImage/"+data.files[i].id);
                	 myDropzone.emit("complete", mockFile);	
                	 myDropzone.options.maxFiles = myDropzone.options.maxFiles - 1;
				} 
        	 }
        	}
        }
    });
}


function submitForm(){
	$("#global-form").validator({
		rules: {
			mobile: function(element, params) {
				var tel =/^(0|86|17951)?(13[0-9]|15[012356789]|17[012356789]|18[0-9]|14[57])[0-9]{8}$/;
			    return tel.test(element.value) || '请检查电话号码';
			}, select_check: function(element, params) {
				var isInvalid = false;
				if(element.value =-1){
					isInvalid=true;
				}
			    return isInvalid||'请选择！';
			},isCheckParty: function(element, params) {
				var isInvalid = false;
				var isParty=$("input[name='isParty']:checked").val()
				if((isParty==1)&&(element.value =='')){
					isInvalid=true;
				}
			    return isInvalid||'请选择！';
			},username: function(element, params) {
				var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
			    return uPattern.test(element.value) || '用户名可以是字母，数字，下划线';
			},
		},
	    fields: {
	    	'nickname':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
			'username':{
				rule : "required;username",
				msg : {
					required : "必填!"
				}
			},
			'password':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
			'deptUser.deptId':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
			phone:{
				rule : "required;mobile",
				msg : {
					required : "必填!"
				}
			},
			'userExtendEO.position':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
			'userExtendEO.education':{
				rule : "required;",
				msg : {
					required : "必填!"
				}
			},
			'userExtendEO.sex':{
				rule : "required;checked",
				msg : {
					required : "必填!"
				}
			},
			'userExtendEO.isParty':{
				rule : "required;checked",
				msg : {
					required : "必填!"
				}
			},
			'userExtendEO.joinPartyDate':{
				rule : "required(isCheckParty)",
				msg : {
					required : "必填!"
				}
			},
	    },
	    invalid: function(form, errors){
	    	console.log(errors);
	    	$(".btn-submit").removeAttr("style");
	    },
	    //验证成功
	    valid: function(form) {
	    	 saveInfo();
	    },
	});
}

function toHtml(data){
	$("select[name='deptUser.deptId']").val(data.deptUser.deptId);
	$("select[name='userExtendEO.education']").val(data.userExtendEO.education);
	$("input[name='userExtendEO.position']").val(data.userExtendEO.position);
	$("input[name='password']").val(1);
	$("input[name='userExtendEO.joinPartyDate']").val(data.userExtendEO.joinPartyDate);
	$("input[name='userExtendEO.sex'][value='"+data.userExtendEO.sex+"']").attr("checked",true); 
	$("input[name='userExtendEO.isParty'][value='"+data.userExtendEO.isParty+"']").attr("checked",true); 
//	$("input[name='isParty']:checked").val();
//	$("input[name='isParty']:checked").val();
//	$("input[name='isParty']:checked").val();
}

function saveInfo(){
	var json =$("#global-form").serializeFormJSON();
	console.log(json);
	var id = $("#id").val();
	var url= ctxPath+"/agency/user/saveInfo";
	if(id!=''&&id!=null){
		url = ctxPath+"/agency/user/updateInfo";
	}
    $.ajax({
    	url: url,
        type: 'POST',
        data: json,
        success: function(d){
        	var success = d.success;
        	if(success){
        	tale.alertOk({
                       text:'保存成功',
                       then: function () {
                           setTimeout(function () {
                               window.location.href = ctxPath+'/agency/user/list';
                           }, 500);
                       }
                   });
        	}else{
        		tale.alertError(d.message || '保存失败');
        	}
        }
    });
}
